//
//  VKPersonInfoController.m
//  V-Learn
//
//  Created by liubo on 2019/1/15.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "VKPersonInfoController.h"
#import "VKPersonInfoCell.h"
#import "VKPersonInfoModel.h"
#import "VKNickController.h"
#import "VKIphoneController.h"
#import "THScrollChooseView.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
@interface VKPersonInfoController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIImageView *imageV;
@property (nonatomic, copy) NSString *headImageString;
@property (nonatomic, strong) NSData *headImageData;

@end

@implementation VKPersonInfoController
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen cz_screenWidth], [UIScreen cz_screenHeight] - LBNAVBAR_HEIGHT) style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 60;
        [self.view addSubview:_tableView];
        _tableView.backgroundColor = [UIColor cz_colorWithRed:244 green:244 blue:244];
        [self setupHeaderView];
        [self setupFooterView];
    }
    return _tableView;
}
- (void)setupHeaderView{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen cz_screenWidth], 102)];
    self.tableView.tableHeaderView = headerView;
    UIButton *bgView = [[UIButton alloc]init];
    [headerView addSubview:bgView];
    bgView.backgroundColor = [UIColor whiteColor];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.height.equalTo(@80);
        make.top.mas_equalTo(headerView).offset(15);
    }];
    [bgView addTarget:self action:@selector(uploadClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.text = @"头像";
    [bgView addSubview:titleLabel];
    titleLabel.textColor = [UIColor cz_colorWithRed:61 green:61 blue:61];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgView);
        make.left.equalTo(@15);
    }];
    
    UIImageView *arrowImageV = [[UIImageView alloc]init];
    arrowImageV.image = [UIImage imageNamed:@"left"];
    [bgView addSubview:arrowImageV];
    arrowImageV.userInteractionEnabled = NO;
    [arrowImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgView);
        make.right.mas_equalTo(-15);
    }];
    
    UIImageView *iconImageV = [[UIImageView alloc]init];
//    iconImageV.image = [UIImage imageNamed:@"girl"];
    [bgView addSubview:iconImageV];
    iconImageV.clipsToBounds = YES;
    iconImageV.contentMode = UIViewContentModeScaleAspectFill;
    iconImageV.userInteractionEnabled = NO;
    _imageV = iconImageV;
    VKPersonInfoModel *model2 = self.dataArray[2];// 性别
    if ([_headImageString containsString:@"http"]) {
        [_headImageString stringByReplacingOccurrencesOfString:Public_URL withString:@""];
    }
    [iconImageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",Public_URL,_headImageString]] placeholderImage:[model2.rightLabel integerValue] == 0 ? [UIImage imageNamed:@"vkgirl"] : [UIImage imageNamed:@"vkboy"]];
    iconImageV.layer.cornerRadius = 55 / 2.0;
    iconImageV.layer.masksToBounds = YES;
    [iconImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgView);
        make.right.mas_equalTo(arrowImageV.mas_left).offset(-10);
        make.width.height.equalTo(@55);
    }];
    
    UIImageView *vipImageV = [[UIImageView alloc]init];
    vipImageV.image = [UIImage imageNamed:@"wk_vip"];
    vipImageV.contentMode = UIViewContentModeScaleAspectFill;
    vipImageV.clipsToBounds = YES;
//    _vipImageV = vipImageV;
    [bgView addSubview:vipImageV];
    vipImageV.userInteractionEnabled = NO;
    vipImageV.layer.cornerRadius = 7.5;
    vipImageV.layer.masksToBounds = YES;
    [vipImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(iconImageV).offset(0);
        make.size.mas_equalTo(CGSizeMake(15, 15));
        make.bottom.mas_equalTo(iconImageV);
    }];
    if ([self.isVip integerValue]==1) {
        vipImageV.hidden = NO;
    }else{
        vipImageV.hidden = YES;
    }
//[self scaleImage:iconImageV.image toScale:0.5];
    UIImage *image = [self imageCompressForWidth:iconImageV.image targetWidth:300];
    _headImageData = UIImageJPEGRepresentation(image, 0.5);
}

- (void)setupFooterView{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen cz_screenWidth], [UIScreen cz_screenHeight] - 102 - 240)];
    self.tableView.tableFooterView = footerView;
    UIButton *commitBtn = [[UIButton alloc]init];
    [footerView addSubview:commitBtn];
    [commitBtn setImage:[UIImage imageNamed:@"vkbtn"] forState:UIControlStateNormal];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(footerView).offset(170);
        make.left.equalTo(@15);
        make.width.equalTo(@([UIScreen cz_screenWidth] - 30));
        make.height.equalTo(@55);
    }];
    commitBtn.imageView.contentMode = UIViewContentModeScaleToFill;
    [commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *commitLabel = [[UILabel alloc]init];
    [footerView addSubview:commitLabel];
    commitLabel.textColor = [UIColor whiteColor];
    commitLabel.font = [UIFont systemFontOfSize:16];
    commitLabel.text = @"保存";
    [commitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(commitBtn).offset(15);
        make.centerX.equalTo(commitBtn);
    }];
}
- (void)commitBtnClick{
    if (!_headImageData) {
        [MBProgressHUD showSuccess:@"请选择头像" toView:self.view];
        return;
    }
    
    VKPersonInfoModel *model0 = self.dataArray[0];// 昵称
    VKPersonInfoModel *model1 = self.dataArray[1];// 年龄
    VKPersonInfoModel *model2 = self.dataArray[2];// 性别
    VKPersonInfoModel *model3 = self.dataArray[3];// 手机号
    
    
    NSString *nickcheng = [model0.rightLabel stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ((nickcheng.length == 0) || [nickcheng isEqualToString:@""]) {
        [MBProgressHUD showSuccess:@"请输入昵称" toView:self.view];
        return;
    }
    NSString *age = [model1.rightLabel stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ((age.length == 0) || [age isEqualToString:@""]) {
        [MBProgressHUD showSuccess:@"请输入年龄" toView:self.view];
        return;
    }
    NSString *sex = [model2.rightLabel stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ((sex.length == 0) || [sex isEqualToString:@""]) {
        [MBProgressHUD showSuccess:@"请输入性别" toView:self.view];
        return;
    }
    NSString *iphone = [model3.rightLabel stringByReplacingOccurrencesOfString:@" " withString:@""];

    if ((iphone.length == 0) || [iphone isEqualToString:@""]) {
        [MBProgressHUD showSuccess:@"请输入手机号" toView:self.view];
        return;
    }
    
    if (![self checkTelNumber:iphone]) {
        [MBProgressHUD showSuccess:@"请输入正确的手机号" toView:self.view];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    NSString *headStr = (self.headImageString == nil)? @"":self.headImageString;
    NSMutableDictionary *dic = @{@"token":[UserModel getUserModel].token,@"username":nickcheng,@"age":@([[age stringByReplacingOccurrencesOfString:@"岁" withString:@""] integerValue]),@"sex":[sex isEqualToString:@"0"] ? @"0":@"1",@"tel":iphone,@"headImg":[headStr stringByReplacingOccurrencesOfString:Public_URL withString:@""]}.mutableCopy;

    [WYHXNetWorkService netWorkSerViceRequestWithPostUrl:WKMeUpdateUserInfo withPostParams:dic withBlock:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        if ([result[@"code"]integerValue] == 200) {
            [MBProgressHUD showSuccess:@"保存成功" toView:self.view];
            [self performSelector:@selector(pop) withObject:nil afterDelay:0.25];
        }else{
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
    }];
}
- (void)pop{
    [self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)checkTelNumber:(NSString *)elNumber{
    NSString *pattern =@"^1+[35789]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    BOOL isMatch = [pred evaluateWithObject:elNumber];
    
    return isMatch;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = @[];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"个人信息";
//    [self tableView];
    [self setupData];
}
- (void)setupData{
    
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    NSString *token = [UserModel getUserModel].token;
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKMeUserInfo withPostParams:@{@"token":token == nil ? @"":token}.mutableCopy withBlock:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        if ([result[@"code"]integerValue] == 200) {
            
             NSString *username;
             NSString *tel;
             NSString *sex; // <null>
             NSString *headImg;// <null>
             NSString *age;// <null>
            
            VKPersonInfoModel *model = [VKPersonInfoModel mj_objectWithKeyValues:result[@"data"]];
            
            if ([model.username isEqual:[NSNull null]]) {
                username = @"";
            }else{
                username = model.username;
            }
            if ([model.tel isEqual:[NSNull null]]) {
                tel = @"";
            }else{
                tel = model.tel;
            }
            if ([model.sex isEqual:[NSNull null]]) {
                sex = @"";
            }else{
                sex = model.sex;
            }
            if ([model.headImg isEqual:[NSNull null]]) {
                headImg = @"";
            }else{
                headImg = model.headImg;
            }
            if ([model.age isEqual:[NSNull null]]) {
                age = @"";
            }else{
                age = model.age;
            }
            _headImageString = headImg;
            [self.dataArray addObject:[[VKPersonInfoModel alloc]initWithLeftLabel:@"昵称" rightLabel:username]];
            [self.dataArray addObject:[[VKPersonInfoModel alloc] initWithLeftLabel:@"孩子年龄" rightLabel:age]];
            [self.dataArray addObject:[[VKPersonInfoModel alloc] initWithLeftLabel:@"性别" rightLabel:sex]];
            [self.dataArray addObject:[[VKPersonInfoModel alloc] initWithLeftLabel:@"手机号" rightLabel:tel]];
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }else{
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
        [self.tableView reloadData];
    }];
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    VKPersonInfoCell *cell = [VKPersonInfoCell cellWithTableView:tableView];
    
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) { // 昵称
        VKNickController *nickIphone = [[VKNickController alloc]initWithRow:indexPath.row];
        nickIphone.infoBlock = ^(NSString * _Nonnull content) {
            [self.dataArray replaceObjectAtIndex:indexPath.row withObject:[[VKPersonInfoModel alloc] initWithLeftLabel:@"昵称" rightLabel:content]];

            [self.tableView reloadData];
        };
        nickIphone.title = @"修改昵称";
        [self.navigationController pushViewController:nickIphone animated:YES];
    }else if (indexPath.row == 1){ // 年龄
        
        NSMutableArray *questionArray = [[NSMutableArray alloc]init];
        for (int i = 3; i <= 8; i++) {
            [questionArray addObject:[NSString stringWithFormat:@"%d岁",i]];
        }
        THScrollChooseView *scrollChooseView = [[THScrollChooseView alloc] initWithQuestionArray:questionArray withDefaultDesc:@"3岁" with:@"选择年龄"];
        [scrollChooseView showView];
        scrollChooseView.confirmBlock = ^(NSInteger selectedQuestion) {
            NSString *suiString = [questionArray[selectedQuestion] stringByReplacingOccurrencesOfString:@"岁" withString:@""];
            [self.dataArray replaceObjectAtIndex:indexPath.row withObject:[[VKPersonInfoModel alloc] initWithLeftLabel:@"年龄" rightLabel:suiString]];
            [self.tableView reloadData];
        };
    }else if (indexPath.row == 2){// 性别
        NSArray *questionArray = @[@"女",@"男"];
        
        THScrollChooseView *scrollChooseView = [[THScrollChooseView alloc] initWithQuestionArray:questionArray withDefaultDesc:@"女" with:@"选择性别"];
        [scrollChooseView showView];
        scrollChooseView.confirmBlock = ^(NSInteger selectedQuestion) {
//            NSLog(@"%@",questionArray[selectedQuestion]);
            [self.dataArray replaceObjectAtIndex:indexPath.row withObject:[[VKPersonInfoModel alloc] initWithLeftLabel:@"性别" rightLabel:[NSString stringWithFormat:@"%ld",(long)selectedQuestion]]];
            [self.tableView reloadData];
        };
    }else if (indexPath.row == 3){// 手机号
        VKIphoneController *nickIphone = [[VKIphoneController alloc]initWithRow:indexPath.row];
        nickIphone.title = @"修改手机号";
        nickIphone.infoBlock = ^(NSString * _Nonnull content) {
            [self.dataArray replaceObjectAtIndex:indexPath.row withObject:[[VKPersonInfoModel alloc] initWithLeftLabel:@"手机号" rightLabel:content]];
            [self.tableView reloadData];
        };
        [self.navigationController pushViewController:nickIphone animated:YES];
    }
}

// 头像
- (void)uploadClick{

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相册选择", nil];
    [actionSheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:{
            
            NSString * mediaType = AVMediaTypeVideo;
            AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
            if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied ) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"未开启摄像头功能" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去开启", nil];
                alert.tag = 11;
                [alert show];
            }else{
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    UIImagePickerController* imagePick = [[UIImagePickerController alloc]init];
                    imagePick.delegate = self;
                    imagePick.allowsEditing = YES;
                    imagePick.sourceType = UIImagePickerControllerSourceTypeCamera;
                    //关键方法
                    dispatch_async(dispatch_get_main_queue(), ^ {
                        [self presentViewController:imagePick animated:YES completion:nil];
                    });
                }else{
                    [MBProgressHUD showSuccess:@"相机不可用，请检测相机设备" toView:self.view];
                    //                        [ShowMessage showTextOnly: messageView:[UIApplication sharedApplication].keyWindow];
                }
            }
            
        }
            break;
        case 1:{
//            NSLog(@"从相册选择");
            UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                pickerImage.navigationBar.translucent = NO;
                pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
                pickerImage.delegate = self;
                pickerImage.allowsEditing = YES;
                [self presentViewController:pickerImage animated:YES completion:nil];
            }else{
                [MBProgressHUD showSuccess:@"相册不可用，请检测手机相册" toView:self.view];
                
                //                    [ShowMessage showTextOnly:@"相册不可用，请检测手机相册" messageView:[UIApplication sharedApplication].keyWindow];
            }
            
        }
            break;
        case 2:
            
            break;
            
        default:
            break;
    }
}
#pragma mark---是否开启摄像头
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            return;
            break;
        case 1:
        {
            if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
                NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if([[UIApplication sharedApplication] canOpenURL:url]) {
                    NSURL *url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    [[UIApplication sharedApplication] openURL:url];
                }
            }else{
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"您没有开启对本应用的相机功能，请开启相机使用权限:设置 > 隐私 > 相机 > 海啸游戏应用，并重新开启本应用！" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
                [alert show];
            }
        }
            break;
            
        default:
            break;
    }
}

#pragma mark---从相册选取
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        [picker dismissViewControllerAnimated:YES completion:^{
            
            if ([info[@"UIImagePickerControllerMediaType"] isEqualToString:@"public.movie"]) {
                [MBProgressHUD showSuccess:@"不能选择视频" toView:self.view];
                return ;
            }
            //原图
            UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
            image = [self imageCompressForWidth:image targetWidth:300];
            _imageV.image = image;

            NSData *data = UIImageJPEGRepresentation(image, 0.5);
            _headImageData = data;
            [self uploadPhoto];
        }];
        
    }else if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        
        UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        image = [self imageCompressForWidth:image targetWidth:200];
        _imageV.image = image;
        //上传图片
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        _headImageData = data;
        [self uploadPhoto];
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
}
// 上传头像
- (void)uploadPhoto{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    NSMutableDictionary *dic = @{@"token":[UserModel getUserModel].token}.mutableCopy;
    VKWeakSelf(self)
    [WYHXNetWorkService uploadSinglePhotoWith:WKMeUploadHeadImage params:dic WithDataArray:@[_headImageData] withParamsArray:@[@"headImg"] AndFinish:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        if ([result[@"code"]integerValue] == 200) {
            [MBProgressHUD showSuccess:@"头像上传成功" toView:self.view];
            weakself.headImageString = [NSString stringWithFormat:@"%@%@",Public_URL,result[@"data"]];
        }else{
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//处理图片
-(UIImage *)imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth
{
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
//缩放图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
//    NSLog(@"%@",NSStringFromCGSize(scaledImage.size));
    return scaledImage;
}
@end
